const express = require("express");
const { sequelize, User } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * @api {get} /admin/charts/sex 获取用户性别统计
 */
router.get("/sex", async function (req, res) {
  try {
    const maleCount = await User.count({ where: { sex: 0 } });
    const femaleCount = await User.count({ where: { sex: 1 } });
    const unkonwnCount = await User.count({ where: { sex: 2 } });
    const data = [
      { value: maleCount, name: "男性" },
      { value: femaleCount, name: "女性" },
      { value: unkonwnCount, name: "未知性别" },
    ];
    return success(res, "获取成功", { data });
  } catch (error) {
    return failure(res, error);
  }
});

router.get("/userMonthCount", async function (req, res) {
  try {
    const [results] = await sequelize.query(
      "SELECT DATE_FORMAT(`createdAt`, '%Y-%m') AS `month`, COUNT(*) AS `value` FROM `Users` GROUP BY `month` ORDER BY `month` ASC"
    );
    const data = {
      months: [],
      values: [],
    };
    results.forEach((item) => {
      data.months.push(item.month);
      data.values.push(item.value);
    });
    return success(res, "获取成功", { data });
  } catch (error) {
    return failure(res, error);
  }
});

module.exports = router;
